//
//  MTWithdrawBindCardController.swift
//  MT
//
//  Created by 陈悦 on 2020/5/25.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import RxSwift
import RxCocoa
import Moya
import Result

class MTWithdrawBindCardController: BaseViewController {
    
    /// MineApi
    private lazy var provider: MTProvider<MineApi> = {
        return MTProvider<MineApi>(plugins: [])
    }()
    
    private let disposeBag = DisposeBag()
    
    private var aliInfoTypes: [UserProfileInfos] = [.aliPayAccount,.realName]
    
    private var bankInfoTypes: [UserProfileInfos] = [.bankAccount,.bankName,.realName]
    
    var isBank: Bool = false
    
    var money: String = ""
    
    /// 真实姓名
    var realName: String?
    /// 支付宝账号
    var aliAccount: String?
    /// 银行卡号
    var bankAccount: String?
    /// 开户行
    var bankName: String?
    
    lazy var tableView: UITableView = {
        let tv = UITableView(frame: self.view.bounds, style: .plain)
        tv.delegate = self
        tv.dataSource = self
        tv.tableFooterView = UIView()
        tv.showsVerticalScrollIndicator = false
        tv.backgroundColor = UIColor(hex: 0xf6f6f6)
        tv.register(MTInfoVerificationInputCell.self, forCellReuseIdentifier: String(describing: MTInfoVerificationInputCell.self))
//        for types in infoTypes {
//            for type in types {
//                register(type.cellClass, forCellReuseIdentifier: String(describing: type.cellClass))
//            }
//        }
        return tv
    }()
    
    lazy var commitButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("提交", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.adjustsImageWhenHighlighted = false
        btn.layer.cornerRadius = 25
        btn.backgroundColor = UIColor(hex:0xffc000)
        btn.clipsToBounds = true
        btn.addTarget(self, action: #selector(withdrawBindCardController(didClickCommitButton:)), for: .touchUpInside)
        return btn
    }()
}

// MARK: ------------------------------------ Overrides ----------------------------------------
extension MTWithdrawBindCardController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        loadData()
        initializeUI()
    }
    
    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
}

// MARK: ---------------------------------------- 初始化 --------------------------------------------
extension MTWithdrawBindCardController {
    
    private func initializeUI() {
        view.backgroundColor = UIColor(hex: 0xf6f6f6)
        navigationItem.title = "账号绑定"
        
        view.addSubview(tableView)
        view.addSubview(commitButton)
        tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        
        commitButton.snp.makeConstraints { (make) in
            make.left.equalTo(view).offset(20)
            make.right.equalTo(view).offset(-20)
            make.height.equalTo(50)
            make.bottom.equalTo(view).offset(-ScreenBottomExtraOffset - 20)
        }
    }
}

extension MTWithdrawBindCardController: UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return isBank ? bankInfoTypes.count : aliInfoTypes.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return isBank ? bankInfoTypes[indexPath.row].cellHeight : aliInfoTypes[indexPath.row].cellHeight
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let infoTypes = isBank ? bankInfoTypes : aliInfoTypes
        let type = infoTypes[indexPath.row]
        guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: MTInfoVerificationInputCell.self), for: indexPath) as? MTInfoVerificationInputCell else {
            return tableView.dequeueReusableCell(withIdentifier: String(describing: MTInfoVerificationInputCell.self), for: indexPath)
        }
        switch type {
            
        case .aliPayAccount, .realName, .bankAccount, .bankName:
            cell.delegate = self
            cell.screenMode = 1
            cell.textFieldTextAlignment = .right
            cell.type = type
            if type == .realName {
                cell.content = realName
            } else if type == .aliPayAccount {
                cell.content = aliAccount
            } else if type == .bankAccount {
                cell.content = bankAccount
            } else if type == .bankName {
                cell.content = bankName
            } 
            return cell
            
        default: break
        }
        
        return cell
    }
}

// MARK: ------------------ input delegate ----------------------
extension MTWithdrawBindCardController: MTInfoVerificationInputCellDelegate {
    func inputCell(_ cell: BaseMTInfoVerificationCell, infoType: UserProfileInfos, didInputText text: String?) {
        switch infoType {
        case .realName:
            self.realName = text
            break
        case .aliPayAccount:
            self.aliAccount = text
            break
        case .bankAccount:
            self.bankAccount = text
            break
        case .bankName:
            self.bankName = text
            break
        default:
            break
        }
    }
    
}

// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MTWithdrawBindCardController {
    private func withdrawBindCardController(didClickCommitButton sender: UIButton) {
        guard checkData() else { return }
        var params: [String: Any] = ["account"    : isBank ? bankAccount! : aliAccount!,
                                     "bankName"   : isBank ? bankName! : "",
                                     "typeId"     : isBank ? 2 : 1,
                                     "userName"   : realName!]
        provider.rx.requestResult(.addAccount(params)).subscribe(onNext: { [weak self] (result: Result<MTWithdrawReportModel, AnyError>, isCache: Bool) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if response.code == 200 {
                    let vc = MTWithdrawConfirmController()
                    vc.money = weakself.money
                    params = ["withdrawMoney": Double(weakself.money) ?? 0]
                    vc.requestParams = params
                    weakself.navigationController?.pushViewController(vc, animated: true)
                } else {
                    AlertManager.presentAlertView(message: response.message ?? "")
                }
                break
                
            case let .failure(error):
                AlertManager.presentAlertView(message: error.localizedDescription)
                break
            }
        }).disposed(by: disposeBag)
    }
    
    private func checkData() -> Bool {
        var isRight = true
        if isBank {
            if bankName?.count == 0 {
                isRight = false
               AlertManager.presentAlertView(message: "请输入开户行")
            }
            
            if bankAccount?.count == 0 {
                isRight = false
               AlertManager.presentAlertView(message: "请输入银行卡号")
            }
            
        } else {
            if aliAccount?.count == 0 {
                isRight = false
               AlertManager.presentAlertView(message: "请输入支付宝账号")
            }
        }
        if realName?.count == 0 {
            isRight = false
           AlertManager.presentAlertView(message: "请输入真实姓名")
        }
        return isRight
    }
    
}

